package com.yn.pet.filter;

import com.alibaba.fastjson2.JSON;
import com.yn.common.constant.HttpStatus;
import com.yn.common.core.domain.AjaxResult;
import com.yn.common.utils.ServletUtils;
import com.yn.common.utils.StringUtils;
import com.yn.pet.entity.model.LoginAppUser;
import com.yn.pet.util.AppTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Slf4j
public class AppTokenFilter extends OncePerRequestFilter {

    private final List<String> excludeUrls = Arrays.asList("/front/app/user/getWxOpenIdByWxCode", "/front/app/user/getUserPhoneByCode");

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        String requestURI = request.getRequestURI();
        if (!excludeUrls.contains(requestURI)) {
            LoginAppUser loginAppUser = AppTokenUtil.getLoginAppUser(request);
            if (loginAppUser == null) {
                int code = HttpStatus.FORBIDDEN;
                String msg = StringUtils.format("请求访问：{}，认证失败，无法访问系统资源", request.getRequestURI());
                ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(code, msg)));
                return;
            }
            AppTokenUtil.verifyToken(loginAppUser);
            AppTokenUtil.putLoginAppUser(loginAppUser);
        }

        filterChain.doFilter(request, response);
        AppTokenUtil.removeLoginAppUser();
    }
}
